package com.youdianstar.app.support

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.youdianstar.app.api.ApiService
import com.youdianstar.app.entity.*
import com.youdianstar.app.common.PAGE_SIZE
import com.youdianstar.app.common.entity.*
import com.youdianstar.app.common.network.model.DataState
import com.youdianstar.app.common.event.NetEventLiveData
import com.youdianstar.app.common.event.NetStateLiveData
import com.youdianstar.app.common.network.BaseRepository
import com.youdianstar.app.common.network.model.BaseResponse
import com.youdianstar.app.support.paging.*
import kotlinx.coroutines.flow.Flow
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import android.util.Log
import com.youdianstar.app.common.util.ApiLogger
import kotlin.collections.mapOf


/**
 * File: ApiRepository
 * Author: 82149 Create: 2021/9/28 19:23
 * Changes (from 2021/9/28)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class ApiRepository(private val service: ApiService) : BaseRepository() {
    companion object {
        //pageSize：每页多少个条目
        //prefetchDistance ：预加载下一页的距离，滑动到倒数第几个条目就加载下一页，无缝加载（可选）默认值是pageSize
        //initialLoadSize ：第一页加载条目数量 ，可选，默认值是 3*pageSize （有时候需要第一页多点数据可用）
        val branchConfig = PagingConfig(
            pageSize = PAGE_SIZE
        )
        val listConfig = PagingConfig(
            pageSize = PAGE_SIZE,
            prefetchDistance = PAGE_SIZE,
            initialLoadSize = PAGE_SIZE,
            enablePlaceholders = false
        )
    }

    /**
     * 获取 系统配置 基础
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun getSystemConfig(stateLiveData: NetStateLiveData<List<ConfigItem>>) {
        executeResp({ service.getSystemConfig(null) }, stateLiveData)
    }

    /**
     * 文件上传
     */
    suspend fun upLoadImage(path: String, stateLiveData: NetStateLiveData<FileUpResult>) {
        val file = File(path)
        val requestFile = RequestBody.create("image/*".toMediaTypeOrNull(), file)
        val part = MultipartBody.Part.createFormData("files", file.name, requestFile)
        executeResp({ service.uploadImageFile(listOf(part), 1) }, stateLiveData)
    }

    /**
     * 删除文件-图片
     */
    suspend fun deleteImage(file: String, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.deleteFile(file) }, stateLiveData)
    }

    /**
     * 判断App版本号
     * @param localVer 本地版本
     * @param netVer 商店版本
     */
    suspend fun checkVersionUpdate(localVer:String,netVer:String,stateLiveData: NetStateLiveData<VersionUpdate>){
        executeResp({service.checkVersionUpdate(state = "0", v1 = localVer, v2 = netVer)},stateLiveData)
    }


    /**
     * 获取 国家码列表
     *
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun getPhoneCodeList(stateLiveData: NetStateLiveData<CodeListRes>) {
        executeResp({ service.getPhoneCodeList() }, stateLiveData)
    }

    /**
     * 获取国家编号
     * ---> IP 默认
     */
    suspend fun getPhoneCodeCurrent(stateLiveData: NetStateLiveData<PhoneCurrent>) {
        executeResp({ service.getPhoneCodeCurrent()}, stateLiveData)
    }

    /**
     * 发送手机登录验证码
     *
     * @param countryCode 国家代码，如 "84" (越南)
     * @param phoneNumber 手机号码
     * @param type 验证码类型，登录时使用 'login'
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun getPhoneTOP(countryCode: String, phoneNumber: String, type: String, stateLiveData: NetStateLiveData<Any>) {
        val params = mapOf(
            "countryCode" to countryCode,
            "phoneNumber" to phoneNumber,
            "type" to type
        )
        ApiLogger.logRequest("发送手机登录验证码", "POST", "sw/app/mobile/login/send_code", params)
        executeResp({ service.getOTPCode(countryCode, phoneNumber, type) }, stateLiveData)
    }

    /**
     * 手机号验证码登录
     *
     * @param countryCode 国家代码，如 "84" (越南)
     * @param phoneNumber 手机号码
     * @param securityCode 验证码
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun loginAccount(countryCode: String, phoneNumber: String, securityCode: String, stateLiveData: NetStateLiveData<MobileLoginResponse>) {
        val params = mapOf(
            "countryCode" to countryCode,
            "phoneNumber" to phoneNumber,
            "securityCode" to securityCode
        )
        ApiLogger.logRequest("手机号验证码登录", "POST", "sw/app/mobile/login", params)
        executeResp({ service.loginAccount(countryCode, phoneNumber, securityCode) }, stateLiveData)
    }

    /**
     * 账号登录 --token登录
     *
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun loginAccountToken(token: String, stateLiveData: NetStateLiveData<UserInfo>) {
        executeResp({ service.loginAccountToken(token) }, stateLiveData)
    }

    /**
     * 退出登录
     */
    suspend fun userLogout(stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.userLogout() }, stateLiveData)
    }

    /**
     * 获取 用户信息 个人中心
     *
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun getUserCenter(stateLiveData: NetStateLiveData<UserCenterResponse>) {
        ApiLogger.logRequest("获取用户中心数据", "GET", "sw/app/ucenter/index.html/V2", null)
        executeResp({ 
            // 直接调用API获取数据，然后包装成BaseResponse格式
            val directResponse = service.getUserCenter()
            val baseResponse = BaseResponse<UserCenterResponse>()
            baseResponse.code = 200
            baseResponse.message = "success"
            baseResponse.setData(directResponse)
            baseResponse
        }, stateLiveData)
    }

    /**
     * 用户-编辑
     *
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun editAccount(loginReq: AccountEdit, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.editUser(loginReq) }, stateLiveData)
    }

    /**
     * 修改昵称
     */
    suspend fun editNickname(userId: Int, nickname: String, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.editNickname(userId, nickname) }, stateLiveData)
    }

    /**
     * 校验原账号
     *
     * @param code 国家/地区码
     * @param phone 手机号
     * @param email 邮箱地址
     * @param msgCode 短信验证码
     */
    suspend fun verifyAccount(code: String?, phone: String?, email: String?, msgCode: String, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.verifyAccount(code = code, phone = phone, email = email, msgCode) }, stateLiveData)
    }

    /**
     * 用户-注销账户
     *
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun userAccountCancel(stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.userAccountCancel() }, stateLiveData)
    }


    /**
     * 账号 -生物识别信息更新
     *
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun accountTouchIdSys(req: TouchIDSys, stateLiveData: NetStateLiveData<Any>){
        executeResp({ service.accountTouchIdSys(req)}, stateLiveData)
    }

    /**
     * 请求网点数据 - 新接口V2
     * 地图页面使用，返回SiteInfo列表并转换为BranchInfo
     */
    suspend fun getMapBranchList(lat: Double, lng: Double, stateLiveData: NetStateLiveData<List<Any>>) {
        executeResp({
            android.util.Log.d("ApiRepository", "========= 地图接口请求参数 =========")
            android.util.Log.d("ApiRepository", "lat=$lat, lng=$lng")
            
            // 注意：API要求 lng在前，lat在后
            val response = service.getMapBranchList(lng = lng, lat = lat, distance = 5, total = 200)
            android.util.Log.d("ApiRepository", "========= 地图接口返回 =========")
            android.util.Log.d("ApiRepository", "code=${response.code}, data大小=${response.data?.size ?: 0}")
            
            // 打印前3条原始数据
            response.data?.take(3)?.forEach { siteInfo ->
                android.util.Log.d("ApiRepository", "原始数据: id=${siteInfo.id}, name=${siteInfo.name}, lat=${siteInfo.lat}, lng=${siteInfo.lng}")
            }
            
            // 将SiteInfo转换为BranchInfo
            val branchList = response.data?.map { siteInfo ->
                siteInfo.toBranchInfo()
            } ?: emptyList()
            
            // 打印前3条转换后的数据
            branchList.take(3).forEach { branchInfo ->
                android.util.Log.d("ApiRepository", "转换后: id=${branchInfo.id}, name=${branchInfo.branchName}, lat=${branchInfo.lat}, lng=${branchInfo.lng}")
            }
            
            android.util.Log.d("ApiRepository", "转换后的BranchInfo数量: ${branchList.size}")
            
            // 手动创建BaseResponse，保持返回List<Any>以兼容现有代码
            val result = com.youdianstar.app.common.network.model.BaseResponse<List<Any>>()
            result.code = response.code
            result.message = response.message
            // 将BranchInfo列表转 Any类型
            result.setData(branchList.map { it as Any })
            result
        }, stateLiveData)
    }

    /**
     * 请求网点数据
     *
     * @param dataType 网点类型：null-全部 1-可租借 2-可归还
     */
    fun getBranchListData(lng: Double, lat: Double, searchKey: String, dataType: Int?, eventLiveData: NetEventLiveData): Flow<PagingData<BranchInfo>> {
        return Pager(branchConfig) {
            BranchPagingSource(service, lng, lat, searchKey, dataType, eventLiveData)
        }.flow
    }

    /**
     * 获取网点详情
     * @param id 网点 id
     * @param lat 纬度
     * @param lng 经度
     * @param distance 距离（公里）
     */
    suspend fun getBranchDetail(id: String, lat: Double, lng: Double, distance: Double, stateLiveData: NetStateLiveData<BranchInfo>) {
        android.util.Log.d("ApiRepository", "获取网点详情: siteId=$id, distance=$distance")
        executeResp(
            { 
                val response = service.getBranchDetails(siteId = id.toInt(), distance = if (distance > 0) distance else null)
                android.util.Log.d("ApiRepository", "详情接口响应: code=${response.code}")
                
                // 手动创建一个BaseResponse<BranchInfo>
                val result = com.youdianstar.app.common.network.model.BaseResponse<BranchInfo>()
                result.code = 200  // 确保code是200
                result.message = response.message
                
                // 转换BranchDetailInfo到BranchInfo
                result.setData(response.data?.toBranchInfo())
                android.util.Log.d("ApiRepository", "转换后的BranchInfo: name=${result.data?.branchName}, rent=${result.data?.rent}, recovery=${result.data?.recovery}")
                
                result
            }, 
            stateLiveData
        )
    }

    /**
     * 判断能否租借
     * @param sno 机柜编号
     */
    suspend fun checkRentOrNot(sno: String,stateLiveData: NetStateLiveData<RentCheck>){
        executeResp({service.rentOrNot(sno)},stateLiveData)
    }


    /**
     * 查询机柜计费规则-默认配置
     * @param sno 机柜编号
     */
    suspend fun requestStationPlan(sno: String, qrUrl: String, stateLiveData: NetStateLiveData<ReqStationPlan>) {
        executeResp({ service.getRentPricePlan(sno, qrUrl) }, stateLiveData)
    }

    /**
     * 获取租借中与未支付订单
     */
    suspend fun getRentingOrder(stateLiveData: NetStateLiveData<OrderQuery>) {
        executeResp({ service.getRentingOrder() }, stateLiveData)
    }
    /**
     * 租借下单 - 预授权
     *
     * @param req 机柜编号 与 其他数据
     */
    suspend fun rentOrderPreAuth(req:RentalAuthRequest,stateLiveData: NetStateLiveData<RentalAuthRes>){
        executeResp({service.rentOrderPreAuth(req)},stateLiveData)
    }

    /**
     * 租借下单
     *
     * @param sno 机柜编号
     */
    suspend fun rentOrder(sno: String, stateLiveData: NetStateLiveData<RentResult>) {
        executeResp({ service.rentOrder(sno) }, stateLiveData)
    }

    /**
     * 查询租借结果-进度条页面用
     *
     * @param orderNo 订单编号
     */
    suspend fun queryRentResult(orderNo: String, stateLiveData: NetStateLiveData<RentResult>) {
        executeResp({ service.queryRentResult(orderNo) }, stateLiveData)
    }

    /**
     * 获取订单数据 列表分页
     */
    fun getOrderListData(eventLiveData: NetEventLiveData): Flow<PagingData<Any>> {
        return Pager(listConfig) {
            OrderPagingSource(service, eventLiveData)
        }.flow
    }

    /**
     * 获取新订单列表数据 - 直接返回数据（不包装在BaseResponse中）
     */
    suspend fun getNewOrderList(stateLiveData: NetStateLiveData<List<Any>>) {
        ApiLogger.logRequest("获取新订单列表", "POST", "sw/app/rentbox/order/list.html/V2", mapOf("status" to 0))
        try {
            // 直接调用API获取OrderListResponse对象
            val requestBody = mapOf("status" to 0)
            val orderListResponse = service.getNewOrderList(requestBody)
            
            // 打印原始响应数据
            android.util.Log.d("ApiRepository", "获取到订单数量: ${orderListResponse.data.size}")
            
            // 截取前20个订单
            val limitedData = orderListResponse.data.take(20)
            android.util.Log.d("ApiRepository", "截取前20个订单: ${limitedData.size}条")
            
            // 手动创建BaseResponse并设置状态
            val baseResponse = BaseResponse<List<Any>>()
            baseResponse.code = 200
            baseResponse.message = "success"
            baseResponse.setData(limitedData)
            baseResponse.dataState = DataState.STATE_SUCCESS
            
            ApiLogger.logResponse("获取新订单列表", baseResponse.code, baseResponse.message, baseResponse.data)
            stateLiveData.postValue(baseResponse)
        } catch (e: Exception) {
            ApiLogger.logException("获取新订单列表", e)
            val baseResponse = BaseResponse<List<Any>>()
            baseResponse.dataState = DataState.STATE_ERROR
            baseResponse.error = e
            stateLiveData.postValue(baseResponse)
        }
    }

    /**
     * 查询订单详情（使用新接口V2）
     *
     * @param orderNo 订单编号或UUID
     * @param onDetailInfoReady 订单详情原始数据回调（可选）
     */
    suspend fun getOrderDetails(
        orderNo: String, 
        stateLiveData: NetStateLiveData<OrderInfo>,
        onDetailInfoReady: ((OrderDetailInfo?) -> Unit)? = null
    ) {
        ApiLogger.logRequest("获取订单详情", "GET", "sw/app/rentbox/order/detail.html/V2", mapOf("orderId" to orderNo))
        try {
            // 直接调用API获取数据
            val directResponse = service.getOrderDetailV2(orderNo)
            
            // 新接口返回的code可能是-1（默认值），说明接口不返回code字段，手动设置为200
            val baseResponse = BaseResponse<OrderInfo>()
            if (directResponse.code == -1 || directResponse.code == 0) {
                baseResponse.code = 200
                baseResponse.message = "success"
            } else {
                baseResponse.code = directResponse.code
                baseResponse.message = directResponse.message
            }
            
            // 设置订单详情数据
            // 新接口返回的是OrderDetailInfo，需要转换为OrderInfo
            val orderDetailInfo = directResponse.data
            if (orderDetailInfo != null) {
                // 先执行回调，确保在主线程设置 currentOrderDetailInfo（通过 ViewModel 的协程切换到主线程）
                // 这里先调用回调，再 postValue，确保数据在观察者执行前已设置
                onDetailInfoReady?.invoke(orderDetailInfo)
                
                // 将新接口数据转换为OrderInfo（用于兼容现有代码）
                val orderInfo = orderDetailInfo.toOrderInfo()
                baseResponse.setData(orderInfo)
                baseResponse.dataState = DataState.STATE_SUCCESS
            } else {
                // 如果data为null，但响应成功，可能是数据结构不匹配，设置为空状态
                baseResponse.dataState = DataState.STATE_EMPTY
                onDetailInfoReady?.invoke(null)
            }
            
            ApiLogger.logResponse("获取订单详情", baseResponse.code, baseResponse.message, baseResponse.data)
            // 延迟一点再 postValue，确保回调先执行完成
            kotlinx.coroutines.delay(10)
            stateLiveData.postValue(baseResponse)
        } catch (e: Exception) {
            ApiLogger.logException("获取订单详情", e)
            val baseResponse = BaseResponse<OrderInfo>()
            baseResponse.code = -1
            baseResponse.dataState = DataState.STATE_ERROR
            baseResponse.error = e
            stateLiveData.postValue(baseResponse)
        }
    }
    
    /**
     * 查询订单详情（旧接口，保留兼容性）
     *
     * @param orderNo 订单编号
     */
    suspend fun getOrderDetailsOld(orderNo: String, stateLiveData: NetStateLiveData<OrderInfo>) {
        executeResp({ service.getOrderDetails(orderNo) }, stateLiveData)
    }


    /**
     * 上报 -租借失败/归还不结束
     * 前置确认充电宝是否在机柜
     */
    suspend fun reportOrderCheck(orderNo: String, stateLiveData: NetStateLiveData<ReportBefore>) {
        executeResp({ service.reportOrderCheck(orderNo) }, stateLiveData)
    }

    /**
     * 订单租借失败/归还不结束
     * @param req 上传数据
     */
    suspend fun reportOrder(req: ReportOrderReq, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.reportOrderFailed(req) }, stateLiveData)
    }

    /**
     * 订单报损
     * @param req 上传数据
     */
    suspend fun reportFault(req: ReportFaultyReq, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.reportFaulty(req) }, stateLiveData)
    }

    /**
     * 获取钱包数据
     */
    suspend fun getWallet(stateLiveData: NetStateLiveData<WalletInfo>){
        executeResp({service.getWallet()},stateLiveData)
    }

    /**
     * 支付-流水列表
     */
    fun getBillRecords(eventLiveData: NetEventLiveData): Flow<PagingData<PaymentRecord>> {
        return Pager(listConfig) {
            RecordPagingSource(service, eventLiveData)
        }.flow
    }

    /**
     * 支付-流水详情
     *
     * @param transferNo 流水号
     */
    suspend fun getBillDetail(transferNo: String, stateLiveData: NetStateLiveData<PaymentRecord>) {
        executeResp({ service.getPaymentBillDetail(transferNo) }, stateLiveData)
    }

    /**
     * 获得优惠券列表-我的优惠券-优惠券主页
     *
     * @param type 0-通用优惠券 1-商家优惠券
     * @param state null-全部 1-未使用 2-已使用 3-已过期
     * @param offset 偏移量 0开始
     */
    suspend fun getCouponsRecord(type: Int?,state: Int?,offset: Int,stateLiveData: NetStateLiveData<List<CouponRes>>){
        executeResp({service.getCouponsRecord(type = type, state = state,offset)},stateLiveData)
    }

    /**
     * 优惠券中心-优惠券列表
     *
     * @param type  0-通用优惠券 1-商家优惠券
     */
    fun getRedeemCouponsPaging(type: Int,eventLiveData: NetEventLiveData): Flow<PagingData<CouponInfo>> {
        return Pager(listConfig) {
            RedeemPagingSource(service, type, eventLiveData)
        }.flow
    }

    /**
     * 兑换优惠券-积分
     *
     * @param id Int
     */
    suspend fun redeemCouponInPoints(id: Int,stateLiveData: NetStateLiveData<Any>){
        executeResp({service.redeemCouponInPoints(id)},stateLiveData)
    }

    /**
     * 兑换优惠券-优惠码
     *
     * @param code 优惠码
     */
    suspend fun redeemCouponWithPromo(code: String,stateLiveData: NetStateLiveData<RedeemResult>){
        executeResp({service.redeemCouponWithPromo(code)},stateLiveData)
    }

    /**
     * 获得优惠码列表-我的优惠码(优惠券主页)
     *
     * @param offset 偏移量 0开始
     */
    suspend fun getPromoCodeRecord(offset: Int,stateLiveData: NetStateLiveData<List<CouponRes>>){
        executeResp({service.getPromoCodeRecord(offset)},stateLiveData)
    }

    /**
     * 获取积分账户
     * @param stateLiveData Callback
     */
    suspend fun getMyPoints(stateLiveData: NetStateLiveData<PointAccount>){
        executeResp({service.getMyPoints()},stateLiveData)
    }

    /**
     * 获取积分规则
     * @param stateLiveData
     */
    suspend fun getPointPlans(stateLiveData: NetStateLiveData<List<PointPlan>>){
        executeResp({service.getPointPlans()},stateLiveData)
    }

    /**
     * 获得积分记录
     *
     * @param type  1-增加 2-使用
     */
    fun getPointRecordPaging(type: Int,eventLiveData: NetEventLiveData): Flow<PagingData<PointRecord>> {
        return Pager(listConfig) {
            PointPagingSource(service, type, eventLiveData)
        }.flow
    }

    /**
     * 获取积分规则 -用户绑卡事件
     * @param stateLiveData Callback
     */
    suspend fun checkPointsBindAction(stateLiveData: NetStateLiveData<List<PointDbResult>>){
        executeResp({service.checkPointsBindAction()},stateLiveData)
    }

    /**
     * 邀请
     * --兑换邀请码
     * @param stateLiveData
     */
    suspend fun getInvitePlans(stateLiveData: NetStateLiveData<List<InviteInfo>>){
        executeResp({ service.getInvitePlans() },stateLiveData)
    }

    /**
     * 邀请--兑换邀请码
     *
     * @param code 邀请码
     */
    suspend fun redeemInvitationCode(code: String,stateLiveData: NetStateLiveData<Any>){
        executeResp({ service.redeemInvitationCode(code) },stateLiveData)
    }


    /**
     * 邀请--获取邀请记录
     *
     * @param offset 偏移量 0开始
     */
    suspend fun getInvitationRecord(offset: Int,stateLiveData: NetStateLiveData<List<InviteRc>>){
        executeResp({ service.getInvitationRecord(offset) },stateLiveData)
    }

    /**
     * 奖励扫码--扫码兑换
     * @param type 1-优惠券 2-优惠码 3-充电卡
     * @param code 编码
     */
    suspend fun scanRewardCode(type: Int,code: String,stateLiveData: NetStateLiveData<Any>){
        executeResp({ service.scanRewardCode(type, code) },stateLiveData)
    }

    /**
     * 充点卡列表-列表主页
     *
     * @param offset 偏移量 0开始
     */
    suspend fun getChargePlanList(offset: Int,stateLiveData: NetStateLiveData<List<ChargePlan>>){
        executeResp({ service.getChargePlanList(offset) },stateLiveData)
    }

    /**
     * 充点卡列表-我的充电卡
     *
     * @param offset 偏移量 0开始
     */
    suspend fun getChargePlanRecord(offset: Int,stateLiveData: NetStateLiveData<List<ChargePlan>>){
        executeResp({ service.getChargePlanRecord(offset) },stateLiveData)
    }

    //----------------------------------商户中心部分---------------------------------------
    /**
     * 店主入住 ---> 邀请链接绑定
     *
     * @param ciphertext 加密文本
     */
    suspend fun merchantLinkAction(ciphertext: String,stateLiveData: NetStateLiveData<MerchantLink>){
        executeResp({service.merchantLinkAction(ciphertext)},stateLiveData)
    }

    /**
     * 招商加盟提交
     * @param name 姓名
     * @param tel 联系电话
     * @param city 城市
     * @param joinNotes 合作意向
     */
    suspend fun submitBusinessJoin(name: String, tel: String, city: String, joinNotes: String, stateLiveData: NetStateLiveData<Any>) {
        val request = mapOf(
            "name" to name,
            "tel" to tel,
            "city" to city,
            "joinNotes" to (joinNotes.ifEmpty { "" })
        )
        android.util.Log.d("ApiRepository", "========= 提交招商加盟 =========")
        android.util.Log.d("ApiRepository", "name=$name")
        android.util.Log.d("ApiRepository", "tel=$tel")
        android.util.Log.d("ApiRepository", "city=$city")
        android.util.Log.d("ApiRepository", "joinNotes=$joinNotes")
        android.util.Log.d("ApiRepository", "完整请求参数: $request")
        executeResp({ service.submitBusinessJoin(request) }, stateLiveData)
    }

    /**
     * 商户中心 ---> 首页统计
     *
     * @param rangeTime 开始时间-结束时间
     */
    suspend fun getMerchantCenterCount(branchId:Int?,rangeTime: String?,stateLiveData: NetStateLiveData<OpMerchantHome>){
        executeResp({service.getMerchantCenterCount(branchId,rangeTime)},stateLiveData)
    }

    /**
     * 商户中心 ---> 提现
     *
     * @param req 请求数据
     */
    suspend fun requestWithdrawal(req: WithdrawsReq, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.requestWithdrawal(req) }, stateLiveData)
    }

    /**
     * 商户中心--获取关联账户
     * @param stateLiveData
     */
    suspend fun getWithdrawalAccount(stateLiveData: NetStateLiveData<List<CardEntity>>){
        executeResp({service.getWithdrawalAccount()},stateLiveData)
    }

    /**
     * 商户中心--订单列表
     *
     * @param offset 偏移量 0开始
     */
    suspend fun getMerchantOrders(branchId:Int?,offset: Int,stateLiveData: NetStateLiveData<List<Any>>){
        executeResp({service.getMerchantOrders(branchId,offset)},stateLiveData)
    }

    /**
     * 商户中心--分成流水
     *
     * @param offset 偏移量 0开始
     */
    suspend fun getMerchantTrans(branchId:Int?,offset: Int,stateLiveData: NetStateLiveData<List<OpTransaction>>){
        executeResp({service.getMerchantTrans(branchId,offset)},stateLiveData)
    }

    /**
     * 商户中心 ---> 分成统计
     *
     * @param branchId 网点ID
     */
    suspend fun getMerchantTransCount(branchId:Int?,stateLiveData: NetStateLiveData<OpTransCount>){
        executeResp({service.getMerchantTransCount(branchId)},stateLiveData)
    }

    /**
     * 商户中心 ---> 提现记录
     *
     * @param offset 偏移量 0开始
     */
    suspend fun getWithdrawalRecord(branchId:Int?,offset: Int,stateLiveData: NetStateLiveData<List<WithdrawalRec>>){
        executeResp({service.getWithdrawalRecord(branchId,offset)},stateLiveData)
    }

    /**
     * 商户中心 ---> 提现记录
     *
     * @param offset 偏移量 0开始
     */
    suspend fun getDeviceList(branchId:Int?,offset: Int,stateLiveData: NetStateLiveData<List<DeviceEntity>>){
        executeResp({service.getDeviceList(branchId,offset)},stateLiveData)
    }

    /**
     * 商户中心 ---> 获取网点列表
     *
     * @param stateLiveData 网络回调
     */
    suspend fun getShopList(stateLiveData: NetStateLiveData<List<MerchantOP>>){
        executeResp({ service.getShopList() }, stateLiveData)
    }

    /**
     * 商户中心--获取网点详情
     *
     * @param branchId 网点ID
     */
    suspend fun getShopDetails(branchId: Int,stateLiveData: NetStateLiveData<OpShopInfo>) {
        executeResp({ service.getShopDetails(branchId) }, stateLiveData)
    }

    /**
     * 商户中心--提现
     *
     * @param req 请求数据
     */
    suspend fun updateShopDetail(req: OpShopRequest, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.updateShopDetail(req) }, stateLiveData)
    }


    /**
     * 商户中心--获取行业列表
     * @param stateLiveData 网络回调
     */
    suspend fun getShopIndustries(stateLiveData: NetStateLiveData<List<OpIndustry>>) {
        executeResp({ service.getShopIndustries() }, stateLiveData)
    }

    /*******************************************旧版接口*************************************/


    /**
     * FAQ 问题列表 - 旧接口
     */
    suspend fun getFaqList(stateLiveData: NetStateLiveData<List<FaqQuestionItem>>) {
        executeResp({ service.getFaqList() }, stateLiveData)
    }

    /**
     * FAQ 问题列表 - 新接口V2（用于查看返回格式）
     */
    suspend fun getFaqListV2(stateLiveData: NetStateLiveData<Any>) {
        executeResp({ 
            val response = service.getFaqListV2()
            android.util.Log.d("ApiRepository", "========= FAQ V2 接口返回 =========")
            android.util.Log.d("ApiRepository", "code: ${response.code}")
            android.util.Log.d("ApiRepository", "message: ${response.message}")
            android.util.Log.d("ApiRepository", "data类型: ${response.data?.javaClass}")
            android.util.Log.d("ApiRepository", "data内容: ${response.data}")
            response
        }, stateLiveData)
    }

    /**
     * Feedback
     */
    suspend fun reportFeedback(req: FeedbackReq, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.reportFeedback(req) }, stateLiveData)
    }


    /**
     * language Switch
     */
    suspend fun languageSwitch(abb: String, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.languageSwitch(abb) }, stateLiveData)
    }


    /**绑卡*/
    suspend fun bindCard(req: CardBindReq, stateLiveData: NetStateLiveData<Any>){
        executeResp({service.bindCard(req)},stateLiveData)
    }

    /**解绑绑卡*/
    suspend fun unBindCard(id:Int,stateLiveData: NetStateLiveData<CardUnbindRes>){
        executeResp({service.unBindCard(id)},stateLiveData)
    }

    /**默认卡卡*/
    suspend fun setDefaultCard(req: CardDefaultReq, stateLiveData: NetStateLiveData<Any>){
        executeResp({service.setDefaultCard(req)},stateLiveData)
    }

    /**押金提现*/
    suspend fun requestRefund(stateLiveData: NetStateLiveData<CardUnbindRes>){
        executeResp({service.requestRefund()},stateLiveData)
    }

    /**
     * 计算支付金额
     *
     * @param type 流水类型：1-租借 3-会员 5-押金 7-报失 11-优惠券 13-购买 15-置换 17-预付款
     * @param orderNo 业务类型
     */
    suspend fun getPaymentPrice(type: Int,orderNo:String?,userCouponId :Int?,chargeCardId: Int?,stateLiveData: NetStateLiveData<OrderInfo>){
        executeResp({service.getPaymentPrice(type,orderNo,userCouponId,chargeCardId)},stateLiveData)
    }

    /**
     * 获取支付方式
     * @param type 业务类型
     */
    suspend fun getPaymentMethod(type:Int,amount :Double,orderNo: String?,stateLiveData: NetStateLiveData<PaymentMethodResult>){
        executeResp({service.getPaymentMethod(type,amount,orderNo)},stateLiveData)
    }

    /**
     * 支付
     * @param req 支付
     */
    suspend fun payment(req: PaymentReq, stateLiveData: NetStateLiveData<PaymentResult>){
        executeResp({service.payment(req)},stateLiveData)
    }


    /**
     * 发送收据
     * @param req 支付
     */
    suspend fun sendReceipts(req: ReceiptReq, stateLiveData: NetStateLiveData<Any>){
        executeResp({service.sendReceipts(req)},stateLiveData)
    }

    /**
     * 创建ZaloPay订单
     * @param deviceId 设备ID
     * @param powerBankType 充电宝类型
     */
    suspend fun createZaloPayOrder(deviceId: String?, powerBankType: Int, stateLiveData: NetStateLiveData<String>){
        executeResp({service.createZaloPayOrder(deviceId, powerBankType)},stateLiveData)
    }

    /**
     * 检查支付状态
     * @param orderUuid 订单UUID
     */
    suspend fun checkPaymentStatus(orderUuid: String, stateLiveData: NetStateLiveData<Any>){
        executeResp({service.checkPaymentStatus(orderUuid)},stateLiveData)
    }

    /**
     * 弹出充电宝接口
     * @param deviceId 设备ID
     */
    suspend fun rentboxPopup(deviceId: String, stateLiveData: NetStateLiveData<Any>) {
        executeResp({ service.rentboxPopup(deviceId) }, stateLiveData)
    }

    /**
     * 获取押金支付配置
     * @param powerBankType 充电宝类型，默认0
     * @param stateLiveData 响应数据
     */
    suspend fun getSecurityPayConfig(powerBankType: Int = 0, stateLiveData: NetStateLiveData<SecurityPayConfigResponse>){
        executeResp({ 
            // 直接调用API获取数据，然后包装成BaseResponse格式（类似getUserCenter的处理方式）
            val directResponse = service.getSecurityPayConfig(powerBankType)
            val baseResponse = BaseResponse<SecurityPayConfigResponse>()
            baseResponse.code = 200
            baseResponse.message = "success"
            baseResponse.setData(directResponse)
            baseResponse
        }, stateLiveData)
    }

    //----------------------------------奖励部分---------------------------------------



    /**
     * 获得优惠券列表-支付页面使用
     *
     * @param orderNo 订单
     */
    suspend fun getCouponList(orderNo: String,stateLiveData: NetStateLiveData<List<CouponRes>>){
        executeResp({service.getCouponList(orderNo)},stateLiveData)
    }

    /**
     * 优惠码-兑换记录 (弃用)
     *
     * @param eventLiveData callback
     */
    fun getPromoRecordPaging(eventLiveData: NetEventLiveData): Flow<PagingData<PromoRecord>> {
        return Pager(listConfig) {
            PromoPagingSource(service, eventLiveData)
        }.flow
    }



    /**
     * 切换 平台
     *
     * @param stateLiveData 带有请求状态的LiveData
     */
    suspend fun setBrandSwitch(req: BrandSwitch, stateLiveData: NetStateLiveData<BrandEntity>) {
        executeResp({ service.setBrandSwitch(req) }, stateLiveData)
    }

    /**
     * 扫码结果 - 查询机柜信息
     * @param deviceId 设备ID
     */
    suspend fun getScanResult(deviceId: String, stateLiveData: NetStateLiveData<Any>) {
        val baseResp = BaseResponse<Any>()
        try {
            baseResp.dataState = DataState.STATE_LOADING
            android.util.Log.d("ApiRepository", "========= 开始请求扫码结果接口 =========")
            android.util.Log.d("ApiRepository", "deviceId=$deviceId")
            
            // 直接使用OkHttp获取原始响应
            val apiService = service as com.youdianstar.app.api.ApiService
            val call = apiService.getScanResult(deviceId)
            val response = call.execute()
            
            android.util.Log.d("ApiRepository", "========= 收到原始响应 =========")
            android.util.Log.d("ApiRepository", "response isSuccess=${response.isSuccessful}")
            
            if (response.isSuccessful && response.body() != null) {
                // 读取原始JSON字符串
                val jsonString = response.body()!!.string()
                android.util.Log.d("ApiRepository", "原始JSON: $jsonString")
                
                // 手动解析JSON
                val gson = com.google.gson.Gson()
                val data = gson.fromJson(jsonString, Map::class.java)
                
                android.util.Log.d("ApiRepository", "解析后的data类型: ${data.javaClass}")
                android.util.Log.d("ApiRepository", "data keys: ${(data as? Map<*, *>)?.keys}")
                
                // 包装响应
                baseResp.code = 200
                baseResp.message = "success"
                baseResp.setData(data)
                baseResp.dataState = DataState.STATE_SUCCESS
                
                android.util.Log.d("ApiRepository", "========= 包装完成 =========")
                android.util.Log.d("ApiRepository", "baseResp.code=${baseResp.code}, data类型=${baseResp.data?.javaClass}")
            } else {
                baseResp.code = response.code()
                baseResp.message = response.message()
                baseResp.dataState = DataState.STATE_FAILED
            }
            
        } catch (e: Exception) {
            android.util.Log.e("ApiRepository", "========= 接口调用异常 =========", e)
            e.printStackTrace()
            baseResp.dataState = DataState.STATE_ERROR
            baseResp.error = e
        }
        
        stateLiveData.postValue(baseResp)
    }

}